package com.rrd.hive.udf;

import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import java.text.SimpleDateFormat;
import java.util.*;

@Description(
        name = "local_date",
        value = "_FUNC_(string) - Obtain local date through country abbreviation .e.g (rpc/mex)",
        extended = "Obtain country local date"
)
public class LocalDateUDF extends UDF {

    public String evaluate(String str) throws HiveException {
        Date date = new Date();
        String zone = TimeZone.getDefault().getID();  //获取当前系统时区

        SimpleDateFormat current = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        current.setTimeZone(TimeZone.getTimeZone(zone));
        String l = current.format(date);  //转换成带时区的时间

        try {
            date = current.parse(l);
        } catch(Exception e) {
            System.out.println("parse error!");
        }

        //切换国家时区 如果时区不在枚举里，默认返回系统时间; 如果未填写，则报错。
        SimpleDateFormat local = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        switch (str) {
            case "mex":
                local.setTimeZone(TimeZone.getTimeZone("America/Mexico_City"));
                l = local.format(date);
                break;
            case "rpc":
                local.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                l = local.format(date);
                break;
            default:
                break;
        }

        return l;
    }

    public static void main(String[] args) throws HiveException {
        String j = new LocalDateUDF().evaluate("xxx");
        System.out.println(j);
    }
}